<template>
  <div class="nav-wrapper">
    <div class="logo">
      <!-- <canvas id="myCanvas" style="width: 180px;height: 110px;"></canvas> -->
      <div class="multiply"></div>
    </div>
    <div class="nav-box">
      <div
        :class="['nav-item', route.path === item.path ? 'active' : '']"
        v-for="(item, index) in navs"
        :key="index"
        @click="handleClickNav(item)"
      >
        <div class="activeBlock" v-if="route.path === item.path"></div>
        <svg-icon
          class="svg-icon"
          :iconName="item.icon"
          :color="
            route.path === item.path ? systemColorReadonly.color : '#a6acb4'
          "
        />
        {{ item.label }}
      </div>
    </div>
    <div class="login">
      <div class="system-paramy" @click="handleSystem">
        <input type="color" id="systemColor" v-model="colorRef" />
        <label for="systemColor">主题色</label>
      </div>
      <div class="user-info">
        <div class="user-cover"
          :style="{backgroundImage:`url(${user.titleSrc ? imageBase + user.titleSrc : defaultTitleSrc })`}"
        ></div>
        <h6 class="user-name">{{ user?.userName }}</h6>

        <el-tooltip content="退出">
          <svg-icon className="svg-icon loginout" iconName="icon-tuichu" :color="systemColorReadonly.color" @click="handleLogout"></svg-icon>
        </el-tooltip>
      
      </div>
    </div>
  </div>
</template>
<script setup name="NavBar">
import { onMounted, onUnmounted, ref, toRef, inject, watch } from 'vue';
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import useSymbols from './../compostions/useSymbols.js';
import hexToRgb from '../../src/util/hexToRgb.js';
import logoSrc from '../assets/imgs/logo-ai.jpg';
import defaultTitleSrc from '../assets/imgs/banner/03.png'
const imageBase = import.meta.env.VITE_BASE_FILE_SRC;
const navs = [
  {
    path: '/index/home',
    label: '首页',
    icon: 'icon-juesecaidan_an',
  },
  {
    path: '/index/book',
    label: '书签和清单',
    icon: 'icon-zidianguanli_an',
  },
  {
    path: '/index/memo',
    label: '便签',
    icon: 'icon-yinhuanjieguo_an',
  },
  {
    path: '/index/photos',
    label: '图库',
    icon: 'icon-yinhuanjieguo_an',
  },
];

const { systemColorReadonly, setSystemColor, initSystem , getUserInfo , logout } = inject(useSymbols);
const user = getUserInfo();

const colorRef = ref(toRef(systemColorReadonly.value.color));
const topRef = ref(0);
const router = useRouter();
const route = useRoute();

const handleClickNav = ({ path, label }) => {
  router.push(path);
};

const scrollFun = () => {
  topRef.value = document.documentElement.scrollTop;
};

// 退出
const handleLogout = async () => {
  await logout();
  ElMessage({
    message: '退出成功！',
    type: 'success',
    duration:1200,
  })
  setTimeout(() => {
    router.replace('/login')
  }, 1200);
}

// 点击颜色按钮，触发input[type=color]颜色选择器
const handleSystem = () => {
  const colorDom = document.querySelector('#systemColor');
  colorDom.click();
};

/**
 * 方便自定义改变logo颜色（使用canvas绘制方式）
 */
const ctxRef = ref();
const imgDataRef = ref();
const mult = 2; //倍数
const canvasLogo = () => {
  const canvas = document.getElementById('myCanvas');
  ctxRef.value = canvas.getContext('2d', { willReadFrequently: true });
  const image = new Image(
    90 * window.devicePixelRatio * mult,
    55 * window.devicePixelRatio * mult
  );
  image.src = logoSrc; // 替换为你的图片路径
  image.onload = function () {
    // 画布的宽高、提高分辨率减少锯齿状
    canvas.width = window.devicePixelRatio * mult * canvas.clientWidth;
    canvas.height = window.devicePixelRatio * mult * canvas.clientHeight;

    ctxRef.value.drawImage(image, 0, 0, this.width, this.height); // 绘制图片
    imgDataRef.value = ctxRef.value.getImageData(
      0,
      0,
      canvas.width,
      canvas.height
    ); // 获取图片数据
    setLogoColor();
  };
};

// 设置变化后的颜色
const setLogoColor = () => {
  const rgbArr = hexToRgb(colorRef.value);
  const data = imgDataRef.value.data; // 获取数据矩阵
  for (let i = 0; i < data.length; i += 4) {
    if (data[i] > 200 && data[i + 1] > 200 && data[i + 2] > 200) {
      data[i] = 255;
      data[i + 1] = 255;
      data[i + 2] = 255;
    } else {
      // 替换为蓝色
      data[i] = rgbArr[0];
      data[i + 1] = rgbArr[1];
      data[i + 2] = rgbArr[2];
    }
  }
  ctxRef.value.putImageData(imgDataRef.value, 0, 0); // 将修改后的数据放回Canvas
};

watch(colorRef, (newColor) => {
  setSystemColor(newColor);
  initSystem('.app');
  // setLogoColor();
});

onMounted(() => {
  window.addEventListener('scroll', scrollFun);
  onUnmounted(() => {
    window.removeEventListener('scroll', scrollFun);
  });

  // canvasLogo();
});
</script>
<style scoped lang="less">
.nav-wrapper {
  width: 180px;
  height: 100%;
  position: relative;
  align-items: center;
  box-sizing: border-box;
  background-color: #ffffff;
  .logo {
    position: absolute;
    top: 10px;
    left: calc(50% - 45px);
    height: 55px;
    width: 90px;
    box-sizing: border-box;
    overflow: hidden;
    color: var(--system-primary-color);
    // 使用css3蒙层（mask）和混合模式（mix-blend-mode）进行图标颜色自定义
    .multiply {
      background-color: var(--system-primary-color);
      width: 85px;
      height: 50px;
      mix-blend-mode: multiply;
      --mask: url('../assets/imgs/note.png') 50% 50% / contain;
      mask: var(--mask);
      --webkit-mask: var(--mask);
    }
  }
  .nav-box {
    margin-top: 10px;
    box-sizing: border-box;
    padding: 70px 14px 0 14px;
    .nav-item {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: start;
      border-radius: 10px;
      padding: 10px 14px 12px 10px;
      cursor: pointer;
      color: #a6acb4;
      margin-bottom: 10px;
      font-size: 14px;
      .svg-icon {
        width: 17px;
        height: 17px;
        font-weight: 600;
        margin-right: 6px;
      }
      .activeBlock {
        position: absolute;
        top: 0;
        left: 0;
        background-color: var(--system-primary-color);
        opacity: 0.08;
        width: 100%;
        height: 100%;
        border-radius: 10px;
        filter: saturate(0.5);
      }
    }
    .active {
      color: var(--system-primary-color);
    }
  }
  .login {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    .system-paramy {
      margin: 0 auto;
      color: var(--system-primary-color);
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid var(--system-primary-color);
      width: 100px;
      height: 30px;
      border-radius: 15px;
      cursor: pointer;
      label {
        cursor: pointer;
      }
      input {
        cursor: pointer;
        width: 18px;
        height: 18px;
        border-radius: 5px;
        background: #fff;
        outline: none;
        padding: 0;
        margin: 0;
        border: none;
        margin-inline-end: 6px;
        &::-webkit-color-swatch-wrapper {
          padding: 0;
          border-radius: 5px;
          border: none;
        }
        &::-webkit-color-swatch {
          position: relative;
          border-radius: 5px;
          border: none;
        }
      }
    }
    .user-info{
      width: 100%;
      background-color: var(--system-active-bg-color);
      display: grid;
      grid-template-columns: 30px 1fr 28px;
      align-items: center;
      padding: 10px 10px;
      margin-top: 10px;
      box-sizing: border-box;
      .user-cover{
        width: 25px;
        height: 0;
        padding-bottom: 25px;
        border-radius: 50%;
        overflow: hidden;
        background-repeat: no-repeat;
        background-position: center center;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        background-size: cover;
        box-sizing: border-box;
      }
      .user-name{
        font-size: 12px;
        font-weight: 400;
        color: #8d8d8d;
        margin: 0;
        padding: 0;
        overflow: hidden;
        width: 100%;
        text-overflow: ellipsis;
        position: relative;
        &::before{
          width: 1px;
          height: 20px;
          position: absolute;
          top: 0;
          right:0;
          background-color: #ddd;
          content: "";
        }
      }
      .loginout{
        width: 18px;
        height: 18px;
        margin-left: 8px;
        cursor: pointer;
        &:hover{
          transform: scale(1.05);
        }
      }
    }
  }
}

</style>